package com.autodesk.akn.emr.service;

import com.autodesk.akn.emr.util.S3Util;
import com.autodesk.akn.emr.web.entity.SPSSConversionParams;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * @author: MaxiRenna
 */
public class FileConverterService {
    private final static Logger LOGGER = Logger.getLogger(FileConverterService.class.getName());
    public static final String IS_FOLDER = "isfolder";
    public static final String HEADERS_ONLY = "headersonly";

    public boolean convertFromSav2Csv(SPSSConversionParams params,List<String>filesToProcess){
        try {

            boolean isFolder = params.getFolder().equals(IS_FOLDER);
            boolean headersOnly = params.getHeadersOnly().equals(HEADERS_ONLY);
            String outputExtension = ".csv";
            //Instantiate S3Util
            S3Util s3Util = new S3Util();
            //Set the correct filesystem
            s3Util.setFileSystem(params.getInputBucket());
            //Copy files from S3 to local
            List<String> files = s3Util.copyFromS3(isFolder, params, filesToProcess);
            if(!files.isEmpty()){
                //Convert the sav files to csv
                List<String> exportedFiles = s3Util.convertSAV2CSV(files,headersOnly,outputExtension);
                if(!exportedFiles.isEmpty()){
                    //Copy the exported files back to S3
                    s3Util.copyToS3(exportedFiles,params.getOutputBucket(),params.getOutputKey(),isFolder);
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return false;
        }

        return true;
    }




}
